<?php
/* 定义这个常量是为了在application.ini中引用*/
define('APPLICATION_PATH',  dirname(__FILE__));
require APPLICATION_PATH . '/vendor/autoload.php';
function exception_handler($exception) {
    // 创建一个新的请求对象，并将当前异常传递给它
    $request = new Yaf\Request\Http();
    $request->setControllerName("Error")
        ->setActionName("error")
        ->setParam("exception", $exception);
    // 调用 YAF 的调度器来处理这个请求
    Yaf\Application::app()->getDispatcher()->dispatch($request);
}
function error_handler($errno, $errstr, $errfile, $errline) {
    // 将错误转换为异常，便于统一处理
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
// 设置自定义的异常和错误处理程序
set_exception_handler('exception_handler');
set_error_handler('error_handler');
$application = new \Yaf\Application( APPLICATION_PATH . "/conf/application.ini");

function parseArrayParam($param) {
    $result = [];
    // 我们假设数组参数格式为 key1:value1,key2:value2,...
    $pairs = explode(',', $param);
    foreach ($pairs as $pair) {
        list($key, $value) = explode(':', $pair);
        $result[$key] = $value;
    }
    return $result;
}

// 获取命令行参数
$params = getopt("", ["module:", "controller:", "action:", "param::"]);
$module = $params['module'] ?? 'Cli';
$controller = $params['controller'] ?? 'index';
$action = $params['action'] ?? 'index';
$paramString = $params['param'] ?? '';

$paramArray = parseArrayParam($paramString);
try {
    $request = new Yaf\Request\Simple("CLI", $module, $controller, $action, $paramArray);
    $application->bootstrap()->getDispatcher()->dispatch($request);
}catch (Exception $exception){
    echo "An exception occurred: " . $exception->getMessage() . "\n";
    exit;
}
?>
